#!usr/bin/env python
#coding=utf8

import threading
import time
import rss
import Queue
import output
from Tkinter import END
from source import feeds
import sys

reload(sys)
sys.setdefaultencoding( "utf-8" )

def timer(fun):
    def wrapped(*args, **kwargs):
        tm=time.clock()
        rst=fun(*args, **kwargs)
        #sys.stdout.write('\n')
        print "\nRunning time = {}".format(time.clock()-tm)
        return rst
    return wrapped

class Manual:
    def __init__(self):
        self.results=[]
        self.lock=threading.RLock()

    def put(self, results):
        if self.lock.acquire():
            self.results.append(results)
            self.lock.release()

class Consumer(threading.Thread):
    def __init__(self, queue, manual):
        threading.Thread.__init__(self)
        self._queue=queue
        self.manual=manual
        #self.parser=parser

    def run(self):
        while True:
            feed=self._queue.get()
            if feed=="quit":
                break
            for item in rss.Parser(feed).run():
                self.manual.put(item)

# @timer
# def Producer():

    # queue= Queue.Queue()
    # manual= Manual()

    # worker_threads=build_worker_pool(queue, manual, 4)

    # for feed in feeds:
        # queue.put(feed)
    
    # for item in worker_threads:
        # queue.put("quit")

    # for worker in worker_threads:
        # worker.join()
       
    # return manual.results
    
    
def build_worker_pool(queue,manual,size):
    workers=[]
    for _ in range(size):
        worker=Consumer(queue,manual)
        worker.start()
        workers.append(worker)
    return workers
    
    
@timer
def Producer():
    from multiprocessing.dummy import Pool as ThreadPool
    
    pool=ThreadPool(4)
    results=pool.map(rss.Parser,feeds)
    
    ans=[]
    for item in results:
        for i in item.run():
            ans.append(i)    
    pool.close()
    pool.join()
    
    return ans

if __name__=="__main__":
    tk=output.OutputBoard()
    rst=Producer()
    outputlist=[str(item) for item in rst]    
    tk.insert(END, outputlist)
    tk.mainloop()
    






